
"""添加对客户的GSP检查"""

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError


class Partner(models.Model):
    _name = 'res.partner'
    _inherit = ['res.partner', 'gsp.manage.base']

    def _nd_get_partner_type_selection(self):
        return self.env['gsp.customer.categ']._fields['type'].selection

    gsp_management = fields.Boolean('是否需要GSP管理', compute="_compute_gsp_management", states={},
                                    store=True, track_visibility='onchange')
    nd_short = fields.Char('简称')
    nd_customer_code = fields.Char('客户编码', readonly=True, unique=True)
    nd_supplier_code = fields.Char('供应商编码', readonly=True, unique=True)
    nd_unify_code = fields.Char('统一社会信用代码')
    nd_legal_person = fields.Char('法定代表')
    nd_response_person = fields.Char('企业负责人')
    nd_reg_capital = fields.Char('注册资本')

    nd_establish_date = fields.Date('成立时间')
    nd_enterprise_type = fields.Char('企业类型')
    nd_customer_type = fields.Selection(selection=_nd_get_partner_type_selection, string='合作伙伴类型')
    nd_customer_categ_id = fields.Many2one('gsp.customer.categ', string='客户GSP类型')
    nd_supplier_categ_id = fields.Many2one('gsp.supplier.categ', string='供应商GSP类型')
    nd_stock_location = fields.Char('库房地址')
    nd_address = fields.Char('住所')

    nd_license_ids = fields.One2many('gsp.license', 'partner_id', string="客户证照")
    nd_grant_ids = fields.One2many('gsp.grant', 'partner_id', string="授权委托书")
    nd_imgs = fields.One2many('nd.product.image', 'partner_id', string='图片')
    nd_files = fields.Many2many('ir.attachment', string='文件', attachment=True)

    @api.constrains('name')
    def _nd_unique_name(self):
        """防止重复"""
        for partner in self:
            same_partners = self.env['res.partner'].sudo().search([('name', '=', partner.name)])
            if (same_partners - partner):
                raise UserError(f'已存在同名联系人：{partner.name}')

    @api.depends('customer', 'supplier', 'nd_customer_categ_id', 'nd_supplier_categ_id')
    def _compute_gsp_management(self):
        for partner in self:
            if partner.customer and partner.nd_customer_categ_id:
                partner.gsp_management = partner.nd_customer_categ_id.gsp_management
            elif partner.supplier and partner.nd_supplier_categ_id:
                partner.gsp_management = partner.nd_supplier_categ_id.gsp_management

    @api.multi
    def confirm(self):
        """在审核的时候，根据相应的GSP类别，检查必要的证照是否完整"""
        res = super().confirm()
        self._check_necessary_licenses()
        return res

    def _check_necessary_licenses(self):
        """根据所选的GSP类别，检查证照完整性"""
        for partner in self:
            if partner.gsp_management:
                need_licenses = self.env['gsp.necessary.license']
                if partner.customer:
                    need_licenses |= partner.nd_customer_categ_id.necessary_license_ids
                    # gsp_categ_id = partner.nd_customer_categ_id
                if partner.supplier:
                    need_licenses |= partner.nd_supplier_categ_id.necessary_license_ids
                    # gsp_categ_id = partner.nd_supplier_categ_id

                offered_licenses = set(partner.nd_license_ids.mapped('template_id').ids)
                # for file in gsp_categ_id.necessary_license_ids:
                for file in need_licenses:
                    necessary_licenses_set = set(file.license_ids.ids)
                    if len(necessary_licenses_set.intersection(offered_licenses)) < file.necessary_count:
                        raise ValidationError(f'合作伙伴需要'
                                              f'提供 {file.license_ids.mapped("display_name")}中'
                                              f'的 {file.necessary_count}种')


    @api.model
    def create(self, vals):
        """增加供应商、客户编码"""
        res = super().create(vals)
        res._nd_add_code()
        return res

    @api.multi
    def write(self, vals):
        """增加供应商、客户编码"""
        res = super().write(vals)
        self._nd_add_code()
        return res

    def _nd_add_code(self):
        """给处于客户或者供应商状态，又没有相应编码的partner增加编码"""
        for partner in self:
            if partner.customer and not partner.nd_customer_code:
                partner.nd_customer_code = self.env['ir.sequence'].next_by_code('nd.res.partner.customer')
            if partner.supplier and not partner.nd_supplier_code:
                partner.nd_supplier_code = self.env['ir.sequence'].next_by_code('nd.res.partner.supplier')

